<?
/********************************************************************************
 * 用户管理类
 ********************************************************************************/
if(!defined('IN_API')){
	$__f_sysvars = VS::get('f_sysvars');
	if(isset($__f_sysvars) && isset($__f_sysvars['ucenter_bridge']) && isset($__f_sysvars['ucenter_bridge']['using']) && $__f_sysvars['ucenter_bridge']['using'] == '1'){
		define('UC_USING', 1);
		define('UC_CONNECT',		$__f_sysvars['ucenter_bridge']['connect']);
	
		define('UC_DBHOST',			$__f_sysvars['ucenter_bridge']['dbhost']);
		define('UC_DBUSER',			$__f_sysvars['ucenter_bridge']['dbuser']);
		define('UC_DBPW',			$__f_sysvars['ucenter_bridge']['dbpass']);
		define('UC_DBNAME',			$__f_sysvars['ucenter_bridge']['dbname']);
		define('UC_DBCHARSET',		'utf8');
		define('UC_DBTABLEPRE',		$__f_sysvars['ucenter_bridge']['dbtablepre']);
		define('UC_DBCONNECT',		$__f_sysvars['ucenter_bridge']['dbconnect']);
	
		define('UC_CHARSET',		'utf-8');
		define('UC_KEY',			$__f_sysvars['ucenter_bridge']['authkey']);
		define('UC_API',			$__f_sysvars['ucenter_bridge']['url']);
		define('UC_APPID',			$__f_sysvars['ucenter_bridge']['appid']);
		define('UC_IP',				$__f_sysvars['ucenter_bridge']['ip']);
		define('UC_PPP',			20);
		include_once LIB_PTH.'uc/uc_client/client.php';
	}
}

class User extends MyBase{
	private $userinfo = array();
	
	function __construct(){
		parent::__construct('user.userid', array('username' => 'username'));
	}
		
	/********************************************************************************
	 * 查询搜索
	 ********************************************************************************/
	
	public function get_userid($username){
		if(!empty($this->userinfo) && $this->userinfo['username'] == $username){
			return $this->userinfo['userid'];
		}
		return $this->db->get_col($this->tbname, array('username' => $username), 'userid');
	}
	
	public function get_by_uid($uid, $fields = '*'){
		if(!empty($this->userinfo) && $this->userinfo['uid'] == $uid){
			return $this->userinfo;
		}
		$userinfo = $this->db->get_row($this->tbname, array('uid' => $uid), $fields);
		if($fields == '*'){$this->userinfo = $userinfo;}
		return $userinfo;
	}
	
	public function get_by_userid($userid, $fields = '*'){
		if(!empty($this->userinfo) && $this->userinfo['userid'] == $userid){
			return $this->userinfo;
		}
		$userinfo = $this->db->get_row($this->tbname, array('userid' => $userid), $fields);
		if($fields == '*'){$this->userinfo = $userinfo;}
		return $userinfo;
	}
	
	public function get_by_username($username, $fields = '*'){
		if(!empty($this->userinfo) && $this->userinfo['username'] == $username){
			return $this->userinfo;
		}
		$userinfo = $this->db->get_row($this->tbname, array('username' => $username), $fields);
		if($fields == '*'){$this->userinfo = $userinfo;}
		return $userinfo;
	}
	
	public function get_by_email($email, $fields = '*'){
		if(!empty($this->userinfo) && $this->userinfo['email'] == $email){
			return $this->userinfo;
		}
		$userinfo = $this->db->get_row($this->tbname, array('email' => $email), $fields);
		if($fields == '*'){$this->userinfo = $userinfo;}
		return $userinfo;
	}
	
	public function get_by_mobile($mobile, $fields = '*'){
		if(!empty($this->userinfo) && $this->userinfo['mobile'] == $mobile){
			return $this->userinfo;
		}
		$userinfo = $this->db->get_row($this->tbname, array('mobile' => $mobile), $fields);
		if($fields == '*'){$this->userinfo = $userinfo;}
		return $userinfo;
	}

	/*******************************************************************************
	 * 读取UCenter用户信息
	 *******************************************************************************/

	public function get_userinfo($username){
		if(defined('UC_USING') && UC_USING == 1){
			$ucinfo = uc_get_user($username, $isuid = 0);
			if(empty($ucinfo)){
				return false;
			}
			$userinfo = array(
				'uid'		=> $ucinfo[0],
				'username'	=> $ucinfo[1],
				'email'		=> $ucinfo[2],
			);
		}else{
			$userinfo = $this->get_by_username($username);
		}
		return $userinfo;
	}
			
	/*public function get_list($fields = '*', $select = array(), $order = array(), $page = 1, $size = 10, $offset = PAGE_OFFSET){
		if(!empty($select['keyword'])){
			$select['kept'] .= " AND `username` LIKE '%{$select['keyword']}%'";
		}
		return $this->db->get_list($this->tbname, $fields, $select, $order, $page, $size, $offset);
	}*/

	/*******************************************************************************
	 * 头像
	 *******************************************************************************/

	public function get_avatar($size = 'small'){
		if(defined('UC_USING') && UC_USING == 1 && $this->userinfo['uid'] > 0){
			return UC_API."/avatar.php?uid={$this->userinfo['uid']}&size={$size}";
		}
		if($size != 'big'){
			return UP_DIR."thumb/{$this->userinfo['avatar']}";
		}
		return UP_DIR.$this->userinfo['avatar'];
	}

	public function uc_avatar_edit(){
		if(defined('UC_USING') && UC_USING == 1 && $this->userinfo['uid'] > 0){
			return uc_avatar($this->userinfo['uid']);
		}
		return '';
	}
	
	/********************************************************************************
	 * 统计
	 ********************************************************************************/
	
	public function get_counts($select = array()){
		return $this->db->get_counts($this->tbname, $select);
	}
			
	/********************************************************************************
	 * 基本方法：检查用户名、邮箱、密码，生成密码
	 ********************************************************************************/
	
	public function check_username($username){
		if(empty($username))return '用户名空';
		$len = strlen($username);
		if($len < 4)return '用户名太短';
		if($len > 20)return '用户名太长';
		if(!preg_match(Cont::REG_USERNAME, $username))return '用户名格式不正确';
		return 'ok';
	}
		
	public function check_password($password){
		if(empty($password))return '未输入密码';
		$len = strlen($password);
		if($len < 6)return '密码太短';
		if($len > 20)return '密码太长';
		if(!preg_match(Cont::REG_PASSWORD, $password))return '密码格式不正确';
		return 'ok';
	}
	
	public function check_mobile($mobile){
		if(empty($mobile))return '手机号码空';
		$len = strlen($mobile);
		if($len != 11)return '手机号码长度不正确';
		if(!preg_match(Cont::REG_MOBILE, $mobile))return '手机号码格式不正确';
		return 'ok';
	}
	
	public function check_email($email){
		if(empty($email))return '未输入邮箱';
		if(!preg_match(Cont::REG_EMAIL, $email))return '邮箱格式不正确';
		return 'ok';
	}
		
	public function generate_password($password){
		return md5(mix_words($password));
	}
	
	/********************************************************************************
	 * 基本操作：增删改
	 ********************************************************************************/
	
	public function register($post){
		if(($msg = $this->check_username($post['username'])) != 'ok')return $this->rwarn($msg);
		if(($msg = $this->check_password($post['password'])) != 'ok')return $this->rwarn($msg);
		if(($msg = $this->check_email($post['email'])) != 'ok')return $this->rwarn($msg);
		if(!empty($post['mobile']) && ($msg = $this->check_mobile($post['mobile'])) != 'ok')return $this->rwarn($msg);
		
		$uid = empty($post['uid']) ? 0 : intval($post['uid']);
		if($uid > 0){
			$this->userinfo = $this->get_by_uid($uid);
			if(!empty($this->userinfo)){
				return $this->update($this->userinfo['userid'], $post);
			}
		}else{

			if($this->get_userid($post['username']) > 0)return $this->rwarn('已存在同名用户');
			if($this->get_by_email($post['email']) > 0)return $this->rwarn('已存在相同邮箱用户');

			if(defined('UC_USING') && UC_USING == 1){
				$uid = uc_user_register($_POST['username'], $_POST['password'], $_POST['email']);
				if($uid <= 0){
					if($uid == -1){
						return $this->rwarn('用户名不合法');
					}elseif($uid == -2){
						return $this->rwarn('包含要允许注册的词语');
					}elseif($uid == -3){
						return $this->rwarn('用户名已经存在');
					}elseif($uid == -4){
						return $this->rwarn('Email 格式有误');
					}elseif($uid == -5){
						return $this->rwarn('Email 不允许注册');
					}elseif($uid == -6){
						return $this->rwarn('该 Email 已经被注册');
					}else {
						return $this->rwarn('注册失败');
					}
				}
			}
		}
		
		$now = TIME;
		$userinfo = array(
			'uid'		=> $uid,
			'username'	=> $post['username'],
			'nickname'	=> empty($post['nickname']) ? '' : $post['nickname'],
			'realname'	=> empty($post['realname']) ? '' : $post['realname'],
			'email'		=> $post['email'],
			'mobile'	=> empty($post['mobile']) ? '' : $post['mobile'],
			'password'	=> $this->generate_password($post['password']),
			'regip'		=> get_ip(),
			'regtime'	=> $now,
			'lsttime'	=> $now,
		);
		$userinfo['userid'] = $this->db->insert($this->tbname, $userinfo);
		if($userinfo['userid'] > 0){
			$this->userinfo = $userinfo;	//$this->get_by_userid($userinfo['userid']);
			$this->userinfo['synjs'] = $this->set_session_cookie();
			return $this->rsucc('', $this->userinfo, 'userinfo');
		}else{
			return $this->rfail($userinfo['userid'], $userinfo, 'userinfo');
		}
	}
	
	/*******************************************************************************
	 * 更新用户信息
	 *******************************************************************************/
	public function update($userid, $post){
		if(!empty($post['password'])){
			// if(($msg = $this->check_password($post['password'])) != 'ok')return $this->rwarn($msg);
			// $post['password'] = $this->generate_password($post['password']);
		}
		$post['updatetime'] = TIME;
		$r = $this->db->update($this->tbname, array('userid' => $userid), $post);
		if($r > 0){
			/* $this->userinfo =  */array_update($this->userinfo, $post);
			$this->userinfo['synjs'] = $this->set_session_cookie();
			return $this->rsucc('', $this->userinfo, 'userinfo');
		}else{
			return $this->rfail($r, $post);
		}
	}

	public function update_avatar($userid, $avatar_old){
		$oUpload = new Upload(array(
			'upload_form_field'	=> 'file_avatar',
			'auto_date_dir'		=> true,
			'out_file_dir'		=> UP_PTH.'avatar/',
			'allowed_file_ext'	=> array('gif', 'jpg', 'jpeg', 'png'),
		));
		$img_arr = $oUpload->upload_process();
		if(!empty($img_arr)){
			//include_once LIB_PTH.'FirePHPCore/fb.php';
			//fb('旧图  = '.$avatar_old);
			if(!empty($avatar_old) && file_exists(UP_PTH.$avatar_old)){	// 删除旧图
				$r = unlink(UP_PTH.$avatar_old);
				//fb('删除：'.UP_PTH.$avatar_old.' = '.$r);
				@unlink(UP_PTH.'thumb/'.$avatar_old);
			}
			$img_path = array_pop($img_arr);			
			$img_path = str_replace(UP_PTH, '', $img_path);
			//File::resize(UP_PTH.$img_path, 200, 150, 'adaptive', UP_PTH.'thumb/'.$img_path);
			$this->update($userid, array('avatar' => $img_path));
			return $this->rsucc('', $img_path, 'path');
		}
		return $this->rwarn();
	}
	
	public function update_thumb($post){
		$file = UP_PTH.$post['avatar'];
		$info = getimagesize($file);
		if($info[0] > 480 || $info[1] > 360){
			if($info[1] / $info[0] > 3 / 4){
				$scale = $info[1] / 360;
			}else{
				$scale = $info[0] / 480;
			}
			$post['cropX'] = $post['cropX'] * $scale;
			$post['cropY'] = $post['cropY'] * $scale;
			$post['cropW'] = $post['cropW'] * $scale;
			$post['cropH'] = $post['cropH'] * $scale;
		}
		$crop = File::crop($file, $post['cropX'], $post['cropY'], $post['cropW'], $post['cropH']);
		$thumb = File::resize($crop, 200, 150, 'adaptive', $crop);
		return true;
	}
	
	// 修改用户密码
	public function edit_password($userid, $oldpwd, $newpwd){
		$msg = $this->check_password($oldpwd);
		if($msg != 'ok') return $this->rwarn($msg);
		$msg = $this->check_password($newpwd);
		if($msg != 'ok') return $this->rwarn($msg);
		
		$row = $this->get_by_userid($userid, '`username`,`password`');

		if($this->generate_password($oldpwd) != $row['password'])return $this->rwarn('原密码不正确');

		if(defined('UC_USING') && UC_USING == 1){
			$ucresult =  uc_user_edit($row['username'], $oldpwd, $newpwd, $email = '', $ignoreoldpw = false);
			if($ucresult <= 0){
				return $ucresult;
			}
		}

		$pwdmd5 = $this->generate_password($newpwd);
		if($oldpwd == $newpwd || $pwdmd5 == $row['password'])return $this->rsucc();	// 如果新密码与原密码相同，直接返回真
		return $this->update($userid, array(
			'password'	=> $pwdmd5,
		));
	}

	// 重置用户密码，不验证旧密码
	public function reset_password($username, $newpwd){
		$msg = $this->check_password($newpwd);
		if($msg != 'ok') return $this->rwarn($msg);

		if(defined('UC_USING') && UC_USING == 1){
			$ucresult =  uc_user_edit($username, '', $newpwd, $email = '', $ignoreoldpw = true);
			if($ucresult < 0){
				if($ucresult == 1){
					return $this->rfail('更新成功');
				}elseif($ucresult == 0){
					return $this->rfail('没有做任何修改');
				}elseif($ucresult == -1){
					return $this->rfail('旧密码不正确');
				}elseif($ucresult == -7){
					return $this->rfail('没有做任何修改');
				}elseif($ucresult == -8){
					return $this->rfail('该用户受保护无权限更改');
				}
			}
		}
		$r = $this->db->update($this->tbname, array('username' => $username), array(
			'password'	=> $pwdmd5,
		));
		return $this->rjust($r);
	}
	
	// 用户中心修改用户账户信息
	public function edit_userinfo($userid, $post){
		$errmsg = array();
		if(!empty($post['nickname']) && strlen($post['nickname']) < 2)$errmsg[] = '未输入昵称或少于2个字';
		if(!empty($post['realname']) && strlen($post['realname']) < 2)$errmsg[] = '未输入真实姓名或少于2个字';
		if(!empty($post['email']) && (strlen($post['email']) < 5 || preg_match(Statics::$rgx['email'], $post['email']) == false))$errmsg[] = '未输入邮箱或格式不正确';
		if(!empty($post['mobile']) && (strlen($post['mobile']) < 5 || preg_match(Statics::$rgx['mobile'], $post['mobile']) == false))$errmsg[] = '未输入手机或格式不正确';
		if(!empty($post['hkid']) && (strlen($post['hkid']) < 15 || idcard_checksum($post['hkid']) == false))$errmsg[] = '未输入身份证或格式不正确';
		if(!empty($errmsg)){
			return $this->rwarn(implode($errmsg));
		}

		if(defined('UC_USING') && UC_USING == 1){
			if(!empty($post['email'])){
				$row = $this->get_by_userid($userid, '`username`');
				$ucresult =  uc_user_edit($row['username'], '', '', $post['email'], $ignoreoldpw = true);
				if($ucresult <= 0){
					return $ucresult;
				}
			}
		}

		if(!empty($post['avatar']) && !empty($post['cropW']) && !empty($post['cropH'])){
			$this->update_thumb($post);
		}
		return $this->update($userid, $post);
	}
	
	/********************************************************************************
	 * 登录验证
	 ********************************************************************************/
	
	public function login($post){
		if(($msg = $this->check_username($post['username'])) != 'ok')return $this->rwarn($msg);
		if(($msg = $this->check_password($post['password'])) != 'ok')return $this->rwarn($msg);
		$uid = 0;
		if(defined('UC_USING') && UC_USING == 1){
			list($uid, $username, $password, $email) = uc_user_login($post['username'], $post['password'], $isuid = 0);
			if($uid <= 0){
				if($uid == -1){
					return $this->rwarn('用户不存在，或者被删除');
				}elseif($uid == -2){
					return $this->rwarn('密码错');
				}else{
					return $this->rwarn('登录失败');	// 未定义
				}
			}
		}
		
		$this->userinfo = $this->get_by_username($post['username'], '*');
		if(empty($this->userinfo)){
			if($uid <= 0){
				return $this->rwarn('用户不存在，或者被删除');
			}
			$post['uid']	= $uid;
			$post['email']	= $email;
			return $this->register($post);
		}

		$data = array(
			'lstip'		=> get_ip(),
			'lsttime'	=> TIME,
		);
		$pwdmd5 = $this->generate_password($post['password']);
		if($pwdmd5 != $this->userinfo['password']){
			if($uid <= 0){
				return $this->rwarn('密码不正确');
			}else{
				$data['password'] = $pwdmd5;	// 更新密码
			}
		}
		// 更新最后登录IP和时间
		$this->db->update($this->tbname, array('userid' => $this->userinfo['userid']), $data);
		$this->userinfo['lsttime'] = TIME;
		$this->userinfo['synjs'] = $this->set_session_cookie($post['remember']);
		return $this->rsucc('', $this->userinfo, 'userinfo');
	}
	
	public function logout(){
		set_session('user', null);
		set_cookie('user', null, -1);
		set_cookie('uname', null, -1);
		session_destroy();
		$synjs = '<script type="text/javascript" charset="utf-8">remove_cookie("user");remove_cookie("uname")</script>';
		// 同步登录
		if(defined('UC_USING') && UC_USING == 1){
			$synjs .= uc_user_synlogout();
		}
		return $synjs;
	}
	
	public function set_session_cookie($expires = 0){
		if(empty($this->userinfo) || empty($this->userinfo['userid']))return false;
		set_session('user', $this->userinfo);

		# 存COOKIE
		if($expires <= 0){
			$expires = strtotime(date('Y-m-d', TIME + 86400)) - TIME;	// 默认今天内有效
		}	
		$userinfo = array(
			'userid'	=> $this->userinfo['userid'],
			'username'	=> $this->userinfo['username'],
			'realname'	=> $this->userinfo['realname'],
			'lsttime'	=> $this->userinfo['lsttime'],
		);
		$str = serialize($userinfo);
		$user = php_authcode($str, 'ENCODE');
		set_cookie('user', $user, $expires);
		set_cookie('uname', $this->userinfo['username'], $expires);
		$uname = empty($this->userinfo['nickname']) ? $this->userinfo['username'] : $this->userinfo['nickname'];
		$synjs = '<script type="text/javascript" charset="utf-8">set_cookie("user", "'.$user.'", '.$expires.');set_cookie("uname", "'.$uname.'", '.$expires.');</script>';

		// 同步登录
		if(defined('UC_USING') && UC_USING == 1){
			$synjs .= uc_user_synlogin($this->userinfo['uid']);
		}
		return $synjs;
	}
	
	public function get_session_cookie(){
		$this->userinfo = get_session('user');
		if(empty($this->userinfo)){
			$user = get_cookie('user');
			if(!empty($user)){
				$userinfo = unserialize(php_authcode($user));
				$this->userinfo = $this->get_by_userid($userinfo['userid']);
				$this->userinfo['synjs'] = $this->set_session_cookie();
			}
		}
		return $this->userinfo;
	}

	/*******************************************************************************
	 * 统计
	 *******************************************************************************/
	public function get_my_stat($userid = 0){
		if($userid <= 0){
			$userid = $this->userinfo['userid'];
		}
		$stat = get_session('user_stat');
// 		if(empty($stat)){
			$oOrder = new Order();
			$oComment = new Comment();
			$oFavorite = new Favorite();
			$stat = array(
				'c_buys'	=> $oOrder->get_counts(array('userid' => $userid)),
				's_cost'	=> $oOrder->get_sum('cost', array('userid' => $userid, 'payment_state' => '2')),
				'c_cmts'	=> $oComment->get_counts(array('userid' => $userid)),
				'c_favs'	=> $oFavorite->get_counts(array('userid' => $userid)),
			);
			if(empty($stat['s_cost'])){$stat['s_cost'] = 0;}
			if($userid == $this->userinfo['userid']){
				set_session('user_stat', $stat);
			}
// 		}
		return $stat;
	}
}
?>
